package com.gyt.manager.common.base.response;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

import java.util.LinkedList;
import java.util.List;

/**
 * @author v_yantgao
 */
@SuppressWarnings("serial")
@Getter
@Setter
@ApiModel(description = "分页对象")
public class Page<T> {

    @ApiModelProperty("分页对象数据")
    private List<T> list;

    @ApiModelProperty("分页对象数据总数")
    private long total;

    @ApiModelProperty("当前页")
    private int pageNum;

    @ApiModelProperty("分页大小")
    private int pageSize;

    @ApiModelProperty("分页页码")
    private int pages;

    public static void startPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
    }

    public static <T> Page<T> from(List<T> data) {
        PageInfo<T> pageInfo = new PageInfo<>(data);
        Page<T> page = new Page<>();
        page.list = data;
        page.total = pageInfo.getTotal();
        page.pageNum = pageInfo.getPageNum();
        page.pageSize = pageInfo.getPageSize();
        page.pages = pageInfo.getPages();
        return page;
    }

    public static <T> Page<T> list2Page(int pageNum, int pageSize, List<T> list){
        Page<T> page = new Page<>();
        //实现list分页
        PageHelper.startPage(pageNum, pageSize);
        int pageStart = pageNum == 1 ? 0 : (pageNum - 1) * pageSize;
        int pageEnd = list.size() < pageSize * pageNum ? list.size() : pageSize * pageNum;
        int pages = list.size() % pageSize == 0 ? list.size() / pageSize : (list.size() / pageSize) + 1;
        List<T> pageResult = new LinkedList<T>();
        if (list.size() > pageStart) {
            pageResult = list.subList(pageStart, pageEnd);
        }
//        PageInfo<T> pageInfo = new PageInfo<T>(pageResult);
//        pageInfo.setTotal(list.size());
//        pageInfo.setPageNum(pageNum);
//        pageInfo.setPageSize(pageSize);
//        pageInfo.setPages(pages);
        page.list = pageResult;
        page.total = list.size();
        page.pageNum = pageNum;
        page.pageSize = pageSize;
        page.pages = pages;
        return page;
    }
}
